#include <Arduino.h>
#include <Wire.h>
#include "main.h"
#include "assitant.h"
#include "jcs_bmp.h"

Adafruit_BMP280 *JCSensor_BMP280::__bmp = NULL;
int JCSensor_BMP280::ins_count = 0;

int JCSensor_BMP280::setup(String &config)
{
    bmp = new Adafruit_BMP280;
    if (!ins_count)
        Wire.begin(SD3, SD2);
    var status = bmp->begin();
    if (!status)
    {
        Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
                         "try a different address!"));
        Serial.print("SensorID was: 0x");
        Serial.println(bmp->sensorID(), 16);
        delete bmp;
        bmp = NULL;
        return -1;
    }
    ins_count++;
    bmp->setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                     Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                     Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                     Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                     Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
    if (!__bmp)
    {
        if (search_fun_in_Lily_ui("bmp") < 0)
            public_a_fun_link_int("bmp", (void *)bmp_detail, 0);
    }
    __bmp = bmp;
    return 0;
}
String JCSensor_BMP280::read()
{
    float val = bmp->readPressure();
    sprintf(tx_back, "\"pressure\":%f", val);
    String res(tx_back);
    return res;
}
JCSensor_BMP280::~JCSensor_BMP280()
{
    if (bmp)
    {
        delete bmp;
        ins_count--;
        if (!ins_count)
            __bmp = NULL;
    }
}
int JCSensor_BMP280::bmp_detail()
{
    if (!__bmp)
        return -1;
    out_(F("Temperature = "));
    out_(__bmp->readTemperature());
    outs(" *C");

    out_(F("Pressure = "));
    out_(__bmp->readPressure());
    outs(" Pa");
    out_(F("Approx altitude = "));
    out_(__bmp->readAltitude(1013.25)); /* Adjusted to local forecast! */
    outs(" m");
    return 0;
}
